package com.iteaj.iot.builder;

import com.iteaj.iot.ProtocolTimeoutManager;
import com.iteaj.iot.FrameworkComponent;
import com.iteaj.iot.IotCoreProperties;
import com.iteaj.iot.event.FrameworkEventListener;
import com.iteaj.iot.handle.proxy.ProtocolHandleProxyMatcher;

import java.util.*;

public class IotApplicationBuilder {

    private Builder server;

    private Builder client;

    /**
     * 配置参数
     */
    private IotCoreProperties properties;

    /**
     * 注册的组件
     */
    private List<FrameworkComponent> components;

    /**
     * 客户端超时管理器
     */
    private ProtocolTimeoutManager clientTimeoutManager;

    /**
     * 服务端超时管理器
     */
    private ProtocolTimeoutManager serverTimeoutManager;

    private Set<ProtocolHandleProxyMatcher> proxyMatchers;

    /**
     * 监听器列表
     */
    private List<FrameworkEventListener> listeners;

    protected IotApplicationBuilder(IotCoreProperties properties) {
        this.properties = properties;
        this.proxyMatchers = new HashSet<>();
        this.listeners = new ArrayList<>(8);
        this.components = new ArrayList<>(16);
    }

    /**
     * 用默认的配置构建
     * @return
     */
    public static IotApplicationBuilder use() {
        return new IotApplicationBuilder(new IotCoreProperties());
    }

    /**
     * 自定义配置构建
     * @param properties
     * @return
     */
    public static IotApplicationBuilder use(IotCoreProperties properties) {
        return new IotApplicationBuilder(properties);
    }

    /**
     * 服务端组件注册
     * @param server {@code ServerBuilder}
     * @return
     */
    public IotApplicationBuilder server(Builder server) {
        this.server = server; return this;
    }

    /**
     * 客户端组件注册
     * @param client {@code ServerBuilder}
     * @return
     */
    public IotApplicationBuilder client(Builder client) {
        this.client = client; return this;
    }

    /**
     * 注册监听器
     * @param listener
     * @return
     */
    public IotApplicationBuilder listener(FrameworkEventListener listener) {
        this.listeners.add(listener); return this;
    }

    /**
     * 注册协议处理器代理
     * @param proxyMatcher
     * @return
     */
    public IotApplicationBuilder proxy(ProtocolHandleProxyMatcher proxyMatcher) {
        this.proxyMatchers.add(proxyMatcher);
        return this;
    }

    /**
     * 注册协议处理器代理
     * @param proxyMatchers
     * @return
     */
    public IotApplicationBuilder proxy(Collection<ProtocolHandleProxyMatcher> proxyMatchers) {
        this.proxyMatchers.addAll(proxyMatchers);
        return this;
    }

    /**
     * 注册协议处理器代理
     * @param proxyMatchers
     * @return
     */
    public IotApplicationBuilder proxy(ProtocolHandleProxyMatcher... proxyMatchers) {
        this.proxyMatchers.addAll(Arrays.asList(proxyMatchers));
        return this;
    }
}
